package cn.lbaicai.controller;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.lbaicai.entity.User;
import cn.lbaicai.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	@RequestMapping("/login")
	public String toLogin(){
		return "logins";
	}
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public Object toLogins(String username,String password){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int code = 201;
		String msg ;
		Subject sub = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		try{
			sub.login(token);
			User user = new User();
			user.setUsername(username);
			User users = userService.selectByUser(user);
			sub.getSession().setAttribute("CurrentUser",users);
			code=200;
			msg="登陆成功";
		}catch (IncorrectCredentialsException ice) {
			msg="密码不正确";
		}catch (UnknownAccountException uae) {
			msg="账号密码不正确";
		}
		resultMap.put("code",code);
		resultMap.put("msg",msg);
		return JSON.toJSON(resultMap);
	}
}
